package com.example.springbootredis.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springbootredis.entity.ApiAccount;
import com.example.springbootredis.service.ApiAccountService;
import com.example.springbootredis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.Map;

/**
 * api account控制器
 */
@RestController
@RequestMapping("api_account")
public class ApiAccountController {
    @Autowired
    private ApiAccountService apiAccountService;
    @Value("${salt}")
    private String salt;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取短信验证码
    @PostMapping("sendCode")
    public JsonResult sendCode(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");

        //验证手机号格式
        if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
            return JsonResult.failed("手机号格式不正确");
        }

        //验证手机号是否重复
        ApiAccount phoneInfo = apiAccountService.findByPhone(phone);
        if(phoneInfo != null){
            return JsonResult.failed("该手机号已经注册");
        }

        //生成验证码
        String code = String.format("%04d", new Random().nextInt(10000));
        stringRedisTemplate.opsForValue().set("code:" + phone, code, 60, TimeUnit.SECONDS);
        System.out.println("手机号 " + phone + " 的验证码为: " + code);
        return JsonResult.success("验证码发送成功", null);
    }

    //注册账号
    @PostMapping("register")
    public JsonResult register(@RequestBody Map<String, String> request) {
        String account = request.get("account");
        String phone = request.get("phone");
        String password = request.get("password");
        String code = request.get("code");

        if(account == null || account.trim().isEmpty()){
            return JsonResult.failed("账号名不能为空");
        }
        if(phone == null || phone.trim().isEmpty()){
            return JsonResult.failed("手机号不能为空");
        }
        if (password == null || password.trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }
        if (code == null || code.trim().isEmpty()){
            return JsonResult.failed("验证码不能为空");
        }

        //验证手机号格式
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return JsonResult.failed("手机号格式不正确");
        }

        //验证验证码
        String redisCode = stringRedisTemplate.opsForValue().get("code:" + phone);
        if(redisCode == null){
            return JsonResult.failed("验证码已过期");
        }
        if(!redisCode.equals(code)){
            return JsonResult.failed("验证码错误");
        }

        //验证账号重复
        ApiAccount accountInfo = apiAccountService.findByAccount(account);
        if(accountInfo != null){
            return JsonResult.failed("该账号已经存在");
        }

        //验证手机号重复
        ApiAccount phoneInfo = apiAccountService.findByPhone(phone);
        if(phoneInfo != null){
            return JsonResult.failed("该手机号已经注册");
        }

        String safePassword = SecureUtil.md5(password);

        //创建用户
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setAccount(account);
        apiAccount.setPhone(phone);
        apiAccount.setPassword(safePassword);

        int result = apiAccountService.addApiAccount(apiAccount);
        if(result == 0){
            return JsonResult.failed("注册失败");
        }

        stringRedisTemplate.delete("code:" + phone);

        return JsonResult.success("注册成功",null);
    }

    @PostMapping("login")
    public JsonResult login(@RequestBody Map<String, String> request) {
        String account = request.get("account");
        String password = request.get("password");

        if(account == null || account.trim().isEmpty()){
            return JsonResult.failed("账号名不能为空");
        }

        if (password == null || password.trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }

        ApiAccount accountInfo = apiAccountService.findByAccount(account);
        if(accountInfo == null) {
            accountInfo = apiAccountService.findByPhone(account);
        }

        if(accountInfo == null || !accountInfo.getPassword().equals(SecureUtil.md5(password))){
            return JsonResult.failed("账号或密码输入错误");
        }

        //生成token,返回给前端
        String token = SecureUtil.sha256(salt + accountInfo.getPassword() + DateUtil.now());

        //使用redis存储,k,v字符串
        stringRedisTemplate.opsForValue().set(token, token, 24*60, TimeUnit.MINUTES);

        return JsonResult.success("登录成功",token);
    }
}